package concurrent;

import util.GsonUtil;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.FutureTask;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @Author Antony
 * @Since 2018/6/20 15:37
 */
public class BaseStudy {

    static Long nanoTime = System.nanoTime();

    public static void main(String[] args) {
        BlockingQueue<String> blockingQueue = new LinkedBlockingQueue(5);
//        BlockingQueue<String> blockingQueue = new MyLinkedBlockingQueue<>(5);

        Thread c1 = new Thread(new Consumer(blockingQueue, "C1_"));
//        Thread c2 = new Thread(new Consumer(blockingQueue, "C2_"));

        Thread p1 = new Thread(new Producer(blockingQueue, "PA_"));
        Thread p2 = new Thread(new Producer(blockingQueue, "PB_"));
        Thread p3 = new Thread(new Producer(blockingQueue, "PC_"));

        c1.start();
//        c2.start();

        p1.start();
        p2.start();
        p3.start();

    }


    private static class Producer implements Runnable{

        BlockingQueue<String> blockingQueue;
        String name;

        public Producer(BlockingQueue<String> blockingQueue, String name) {
            this.blockingQueue = blockingQueue;
            this.name = name;
        }

        @Override
        public void run() {
            System.out.println(String.format("Producer Thread %s start...", name));
            int count =  0;
            while (count < 20){
                if(count%5 == 0){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                //阻塞的put
                try {
                    blockingQueue.put(name + (System.nanoTime()-nanoTime));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                count++;
            }
        }
    }

    private static class Consumer implements Runnable{
        BlockingQueue<String> blockingQueue;
        String name;

        public Consumer(BlockingQueue<String> blockingQueue, String name) {
            this.blockingQueue = blockingQueue;
            this.name = name;
        }

        @Override
        public void run() {
            System.out.println(String.format("Consumer Thread %s start...", name));
            while (true){
                try {
                    String str = blockingQueue.take();
                    System.out.println(String.format("Consumer Thread %s take %s", name, str));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }
    }
}
